//
//  SelInviteViewController.m
//  Growth
//
//  Created by 洪波 陈 on 5/17/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "SelInviteViewController.h"

#import "RegexKitLite.h"

@interface SelInviteViewController ()

@end

@implementation SelInviteViewController

@synthesize phoneNum;
@synthesize emailAddress;
@synthesize bgView;

- (void)dealloc
{
    CLog(@"SelInviteView released!");
    
    [phoneNum release];
    [emailAddress release];
    [bgView release];
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //背景阴影效果
    bgView.layer.cornerRadius = 3;
    bgView.layer.shadowOpacity = 0.4;
	bgView.layer.shadowRadius = 1.5;
	bgView.layer.shadowOffset = CGSizeMake(0, 0);
    CGRect shadowFrame = bgView.layer.bounds;
    CLog(@"shadow frame rect %f, %f, %f, %f", shadowFrame.origin.x, shadowFrame.origin.y, shadowFrame.size.width, shadowFrame.size.height);
    CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(shadowFrame.origin.x, shadowFrame.origin.y -1, shadowFrame.size.width, shadowFrame.size.height)].CGPath;
    bgView.layer.shadowPath = shadowPath;
    
    //定义左侧按钮
    UIBarButtonItem * rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"发送" style:UIBarButtonSystemItemDone target:self action:@selector(postInviteAction:)];   
    [[self navigationItem] setRightBarButtonItem:rightBarButtonItem];  
    [rightBarButtonItem release];
    
    //定义返回按钮
    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
    
    [[self navigationItem] setBackBarButtonItem:backBarButtonItem];  
    [backBarButtonItem release];
    
    self.navigationItem.title = @"邀请";

    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma mark TextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{

    [textField becomeFirstResponder];
    if (textField == phoneNum) {
        emailAddress.text = @"";
    }
    else if(textField == emailAddress){
        phoneNum.text = @"";
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES; 
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{

}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


#pragma mark -
#pragma mark Action

- (void)postInviteAction:(id)sender
{
    [emailAddress resignFirstResponder];
    [phoneNum resignFirstResponder];
    
    NSString *email = emailAddress.text;
    
    NSString *phone = phoneNum.text;
    
    
    
    if(phone != nil && ![phone isEqualToString:@""]){
        [self sendSMSWith:phone];
    }
    else if(email != nil && ![email isEqualToString:@""]) {
        [self sendEmailWith:email];
    }
    else {
        [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"请输入手机号或邮箱地址！" duration:DEFAULT_LOADING_TIME];
    }
}



#pragma mark -
#pragma mark Compose Mail/SMS


- (void)sendSMSWith:(NSString *)phoneNumStr
{
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
	
	if (messageClass != nil) { 			
		// Check whether the current device is configured for sending SMS messages
		if ([messageClass canSendText]) {
			[self displaySMSComposerSheetWith:phoneNumStr];
		}
		else {	
			[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不支持发短信哦！" duration:DEFAULT_LOADING_TIME];
            
		}
	}
	else {
		[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不支持发短信哦！" duration:DEFAULT_LOADING_TIME];
	}
}


- (void)sendEmailWith:(NSString *)email
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    
	if (mailClass != nil) {
        //[self displayMailComposerSheet];
		// We must always check whether the current device is configured for sending emails

        if ([mailClass canSendMail]) {
			[self displayMailComposerSheetWith:email];
		}
		else {
			[self launchMailAppOnDeviceWith:email];
		}
	}
	else	{
		[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不能发邮件哦！" duration:DEFAULT_LOADING_TIME];
	}
}

// Displays an email composition interface inside the application. Populates all the Mail fields. 
-(void)displayMailComposerSheetWith:(NSString *)emailStr 
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	[picker setSubject:@"我正在使用印象宝贝"];
	
	
	// Set up recipients
	NSArray *toRecipients = [NSArray arrayWithObject:emailStr]; 
	
	[picker setToRecipients:toRecipients];
	
	// Attach an image to the email
//	NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"jpg"];
//	NSData *myData = [NSData dataWithContentsOfFile:path];
//	[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];
	
	// Fill out the email body text
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *bodyStr = [NSString stringWithFormat:@"我正在使用印象宝贝，如果你通过http://www.lanbaoo.com/app/download  下载，就可以和我一起分享宝宝的成长啦。记得加我为好友哦，我的昵称是%@。【印象宝贝——移动互联时代儿童成长亲密助手】",userNickName ];
	[picker setMessageBody:bodyStr isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}

// Launches the Mail application on the device.
-(void)launchMailAppOnDeviceWith:(NSString *)emailStr
{
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *bodyStr = [NSString stringWithFormat:@"我正在使用印象宝贝， 如果你通过http://www.lanbaoo.com/app/download 下载，就可以和我一起记录并分享宝宝的精彩瞬间啦。记得加我为好友哦，我的昵称是%@。 【印象宝贝——移动互联时代儿童成长亲密助手】",userNickName ];
    
	NSString *recipients = [NSString stringWithFormat:@"mailto:%@?subject=我正在使用印象宝贝", emailStr] ;
	NSString *body = [NSString stringWithFormat:@"&body=%@", bodyStr] ;
    
	
	NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

// Displays an SMS composition interface inside the application. 
-(void)displaySMSComposerSheetWith:(NSString *)phoneNumStr 
{
	MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
    
    NSArray *phoneArray = [NSArray arrayWithObjects:phoneNumStr, nil];
    
    [picker setRecipients:phoneArray];
    
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *bodyStr = [NSString stringWithFormat:@"我正在使用印象宝贝，如果你通过http://www.lanbaoo.com/app/download  下载，就可以和我一起分享宝宝的成长啦。记得加我为好友哦，我的昵称是%@。【印象宝贝——移动互联时代儿童成长亲密助手】",userNickName ];
    [picker setBody: bodyStr];
    
	picker.messageComposeDelegate = self;
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}
#pragma mark -
#pragma mark Dismiss Mail/SMS view controller

// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the 
// message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller 
          didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件已取消"];
			break;
		case MFMailComposeResultSaved:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件已保存"];
			break;
		case MFMailComposeResultSent:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件已发送"];
			break;
		case MFMailComposeResultFailed:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件发送失败"];
			break;
		default:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件发送失败"];
			break;
	}
	[self dismissModalViewControllerAnimated:YES];
}


// Dismisses the message composition interface when users tap Cancel or Send. Proceeds to update the 
// feedback message field with the result of the operation.
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller 
                 didFinishWithResult:(MessageComposeResult)result {
    
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MessageComposeResultCancelled:
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"短信已取消"];
			break;
		case MessageComposeResultSent:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"短信已发送"];
			break;
		case MessageComposeResultFailed:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"短信发送失败"];
			break;
		default:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"短信发送失败"];
			break;
	}
	[self dismissModalViewControllerAnimated:NO];
}


@end
